//
//  Client_RF225_PutAwayController.swift
//  Wmsmobile
//
//  Created by xuNick on 16/9/8.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class Client_RF225_PutAwayController: HDFounctionBaseController , HDBarcodeInputCellInputDelegate , HDSwitchCellDelegate , HDFounctionBottomViewDelegate , HDKeyboardInputCellDelegate , HDNumberInputCellDelegate {
    //MARK: - property
    let dataArray:[[String]] = [
    ["托盘条码","货品代码","货品名称","规格","箱数/上架"],
    ["建议货位"],
    ["上架货位","校验码","建议件数","整件/零散"]
    ]
    
    lazy fileprivate var bottomView:HDFounctionBottomView = {
        let view = HDFounctionBottomView(array: ["上架" , "上架异常"])
        return view
    }()

    //MARK: - lifeCycle
    override func viewDidLoad() {
        self.tableView.register(HDBarcodeInputCell.self, forCellReuseIdentifier: "HDBarcodeInputCell")
        self.tableView.register(HDProductInfocell.self, forCellReuseIdentifier: "HDProductInfocell")
        self.tableView.register(HDSwitchCell.self, forCellReuseIdentifier: "HDSwitchCell")
        self.tableView.register(HDKeyboardInputCell.self, forCellReuseIdentifier: "HDKeyboardInputCell")
        self.tableView.register(HDNumberInputCell.self, forCellReuseIdentifier: "HDNumberInputCell")
        self.tableView.addSubview(self.bottomView)
        self.tableView.contentInset.bottom = bottomView.height
        self.bottomView.delegate = self
        super.viewDidLoad()
    }
    override func viewDidAppear(_ animated: Bool) {
        let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 0)) as! HDBarcodeInputCell
        cell.state = inputViewState.activated
    }
    //MARK: - delegate
    func finishNumInput(_ cell: HDNumberInputCell) {
        self.outAway(cell)
    }
    func clicKKeyboardReturn(_ cell: HDKeyboardInputCell){
        let indexpath = self.tableView.indexPath(for: cell)!
        switch (indexpath as NSIndexPath).section * 20 + (indexpath as NSIndexPath).row  {
        case 41:
        let lastCell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
        if lastCell.codeInputView.textField.text == downloadData["poBinCode"] {
            self.goNextCell(cell, nextInsexPath: IndexPath(row: 3, section: 2))
        }else{
            cell.state = inputViewState.disabled
            let nextCell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
            nextCell.state = inputViewState.wrong
            self.showMessage("输入货位与建议货位不一致", success: false)
        }
        default:
            break

    }
    }
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.bottomView.y = KscreenHeight - bottomView.height + self.tableView.contentOffset.y
    }
    func clickFounctionBottom(_ position: NSInteger) {
        switch position {
        case 0:
            if let cell = self.tableView.cellForRow(at: IndexPath(item: 3, section: 2)) as? HDNumberInputCell {
                let putawayCell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as? HDBarcodeInputCell
                guard putawayCell?.codeInputView.textField.text?.characters.count > 0 else{
                    return
                }
                self.activedCell?.state = inputViewState.disabled
                let lastCell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
                let piQpc = "\(cell.boxNumberTextField.text ?? "0")+\(cell.bagNumberTextField.text ?? "0")"
                if lastCell.codeInputView.textField.text == downloadData["poBinCode"] {
                    if piQpc.characters.count == 0 {
//                    cell.codeInputView.textField.text = downloadData["poSuggestQpc"]
                        let SuggestQpc = downloadData["poSuggestQpc"]
                        let stringArr = SuggestQpc?.components(separatedBy: "+")
                        cell.boxNumberTextField.text = stringArr?.first
                        if stringArr?.count > 1 {
                            cell.bagNumberTextField.text = stringArr?.last
                        }
                }
                cell.state = inputViewState.activated
              self.outAway(cell)
            }else{
                cell.state = inputViewState.disabled
                let nextCell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
                nextCell.state = inputViewState.wrong
                self.showMessage("输入货位与建议货位不一致", success: false)
            }
            }
        case 1:
            //先确定上架货位是否有信息
            if let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as? HDBarcodeInputCell{
                if let string = cell.codeInputView.textField.text {
                    if string.characters.count == 0 {
                        return
                    }
                    NetworkTool.sharedTools.postSoap(["piBinCode" : string , "piOperator" : (userInfo?.userName)!], bodyMethod: "PutAwayExcept", suffix: "330", success: { (data) in
                        if let dict = analysisManager.shareManager.XmlParserAnalysis(XMLParser(data: data), elementName: "PutAwayExceptResponse").first{
                            self.downloadData += dict
                            if dict["PutAwayExceptResult"] == "0" {
                                self.tableView.endEditing(true)
                                self.reuseFlag = false
                                self.tableView.reloadData()
                                self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 0))
                                self.downloadData.removeAll()
                                self.reuseFlag = true
                            }else{
                                self.showMessage(self.downloadData["poErrMsg"]!, success: false)
                            }
                        }
                        }, failed: {
                            
                    })
                }
            }
        case 2:
            print("2")
        case 3:
            print("3")
        default:
            break
        }
    }
    func clickSwitch(_ isOn: Bool) {
        if isOn{
            if let cell = self.tableView.cellForRow(at: IndexPath(item: 3, section: 2)) as? HDNumberInputCell{
                let SuggestQpc = downloadData["poSuggestQpc"]
                let stringArr = SuggestQpc?.components(separatedBy: "+")
                cell.boxNumberTextField.text = stringArr?.first
                if stringArr?.count > 1 {
                    cell.bagNumberTextField.text = stringArr?.last
                }
            }
        }else{
            if let cell = self.tableView.cellForRow(at: IndexPath(item: 3, section: 2)) as? HDNumberInputCell{
                cell.boxNumberTextField.text = nil
                cell.bagNumberTextField.text = nil
            }
        }
    }
    func clicKReturn(_ cell: HDBarcodeInputCell) {
        let indexpath = self.tableView.indexPath(for: cell)!
        switch (indexpath as NSIndexPath).section * 20 + (indexpath as NSIndexPath).row  {
        case 0: //第一个cell回车
            guard cell.codeInputView.textField.text != nil else{
                self.showMessage("请输入托盘条码", success: false)
                return
            }
             //TODO: 注意，输入框没有文字时不允许点击回车
            self.downloadData += ["piPalletCode" : cell.codeInputView.textField.text!]
            NetworkTool.sharedTools.postSoap(["piPalletCode" : cell.codeInputView.textField.text! , "piFlag" : "5" , "piUser" : (userInfo?.userName)! , "piStkin" : ""], bodyMethod: "handlePallet", suffix: nil, success: { (data) in
                if let dict = analysisManager.shareManager.XmlParserAnalysis(XMLParser(data: data), elementName: "handlePalletResponse").first{
                    self.downloadData += dict
                    if dict["handlePalletResult"] == "0" { //handlePallet 成功
                        NetworkTool.sharedTools.postSoap(["piPalletCode" :  cell.codeInputView.textField.text! , "piOperator" : (userInfo?.userName)! , "piType" : "0"], bodyMethod: "getBin", suffix: "330", success: { (data) in
                            if let dict = analysisManager.shareManager.XmlParserAnalysis(XMLParser(data: data), elementName: "getBinResponse").first{
                                self.downloadData += dict
                                if dict["getBinResult"] == "0" { //getBin 成功
                                    let getBinResultCell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 1)) as! HDProductInfocell
                                    getBinResultCell.textField.text = dict["poBinCode"]
                                    //展示cell的方法
                                    for i in 1..<5 { //给需要的地方赋值
                                        let cell = self.tableView.cellForRow(at: IndexPath(item: i, section: 0)) as! HDProductInfocell
                                        switch i {
                                        case 1:
                                            cell.textField.text = dict["poArticleCode"]
                                        case 2:
                                            cell.textField.text = dict["poArticleName"]
                                        case 3:
                                            cell.textField.text = dict["poSpec"]
                                        case 4:
                                            cell.textField.text = (dict["poQpc"] ?? "0")  + "/" + (dict["poSuggestQpc"] ?? "0")
                                        default:
                                            break
                                        }
                                    }
                                    self.oneToManyHandler(dict["poArticleCode"]!, piOwner: "-1", piBin: nil, success: { (dict) in
                                        if let gid = dict["内码"]{
                                            NetworkTool.sharedTools.postSoap(["piArticle" : gid ], bodyMethod: "GetArticlePickBin", suffix: "330", success: { (data) in
                                                if let dict = analysisManager.shareManager.XmlParserAnalysis(XMLParser(data: data), elementName: "GetArticlePickBinResponse").first{
                                                    self.downloadData += dict
                                                    if dict["GetArticlePickBinResult"] == "0" { //GetArticlePickBin 成功
                                                        cell.state = inputViewState.disabled
                                                        let nextCell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 2)) as! HDBarcodeInputCell
                                                        nextCell.state = inputViewState.activated
                                                    }else{
                                                        self.showMessage(self.downloadData["poErrMsg"]!, success: false)
                                                        cell.state = .wrong
                                                    }
                                                }
                                                }, failed: {
                                                    
                                            })
                                        }

                                        }, failed: {
                                            
                                    })
                                    
                                }else{
                                    self.showMessage(self.downloadData["poErrMsg"]!, success: false)
                                    cell.state = .wrong
                                }
                            }
                        }, failed: { 
                            print("请求失败")
                     })
  
                    }else{
                        self.showMessage(self.downloadData["poErrMsg"]!, success: false)
                         cell.state = .wrong
                    }
                }
                
                }, failed: { //handlePallet 失败
                    cell.state = .wrong
            })
        case 40:
            self.goNextCell(cell, nextInsexPath: IndexPath(item: 1, section: 2))
           default:
            break
        }
        
    }
    //MARK: - private
    override func isEmpty() -> (Bool) {
        if let cell = self.tableView.cellForRow(at: IndexPath(item: 1, section: 0)) as? HDProductInfocell{
            if cell.textField.text?.characters.count > 0 {
                return false
            }else{
                return true
            }
        }else{
            return false
        }
    }
    func outAway(_ cell: HDNumberInputCell){
        let piPalletCode = downloadData["piPalletCode"]
        let piQpc = "\(cell.boxNumberTextField.text ?? "0")+\(cell.bagNumberTextField.text ?? "0")"
        NetworkTool.sharedTools.postSoap(["piBinCode" : downloadData["poBinCode"]! , "piParityBit" : "" , "piPalletCode" : piPalletCode! , "piOperator" : (userInfo?.userName)! , "piType" : "0" , "piQpc" : piQpc], bodyMethod: "finishPutAway", suffix: "330", success: { (data) in
            if let dict = analysisManager.shareManager.XmlParserAnalysis(XMLParser(data: data), elementName: "finishPutAwayResponse").first{
                self.downloadData += dict
                if dict["finishPutAwayResult"] == "0" { //上架成功
                    self.showMessage("上架成功", success: true)
                    //TODO: 上架完了就清屏，没完接着给上架
                    let numDone = self.getNumberByString( piQpc, standard: self.downloadData["poSpec"]!)
                    let numAll = self.getNumberByString(self.downloadData["poQpc"]!, standard: self.downloadData["poSpec"]!)
                    if numDone < numAll {
                        let cellSwitch =  self.tableView.cellForRow(at: IndexPath(item: 2, section: 2)) as! HDSwitchCell
                        cellSwitch.switchView.isOn = false
                        for i in 0...3 {
                            switch i {
                            case 0,1,3:
                                let cellToclear = self.tableView.cellForRow(at: IndexPath(item: i, section: 2)) as! HDFounctionBaseCell
                                cellToclear.clearContent()
                                break
                            default:
                                break
                            }
                        }
                        self.goNextCell(self.activedCell!, nextInsexPath: IndexPath(item: 0, section: 0))
                        let cellFirst = self.tableView.cellForRow(at: IndexPath(item: 0, section: 0)) as! HDBarcodeInputCell
                        self.clicKReturn(cellFirst)

                    }else{
                        self.reuseFlag = false
                        self.tableView.reloadData()
                        self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 0))
                        self.downloadData.removeAll()
                        self.reuseFlag = true
                    }
                }else{ //不成功 焦点给到上架货位
                    self.showMessage(dict["poErrMsg"]!, success: false)
                    let cellSwitch =  self.tableView.cellForRow(at: IndexPath(item: 2, section: 2)) as! HDSwitchCell
                    cellSwitch.switchView.isOn = false
                    for i in 0...3 {
                        switch i {
                        case 0,1,3:
                            let cellToclear = self.tableView.cellForRow(at: IndexPath(item: i, section: 2)) as! HDFounctionBaseCell
                            cellToclear.clearContent()
                            break
                        default:
                            break
                        }
                    }
                    self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 2))
                    
                }
            }
            }, failed: {
                
        })
    }
    //MARK: - tableviewDatasource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray[section].count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellOriginal:HDFounctionBaseCell?
        switch ((indexPath as NSIndexPath).section) * 100 + ((indexPath as NSIndexPath).row) {
        case 0:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.InputDelegate = self
            
        case 200:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.InputDelegate = self
        case 201:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDKeyboardInputCell") as! HDKeyboardInputCell
            let cell = cellOriginal as! HDKeyboardInputCell
            cell.InputDelegate = self
        case 203:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDNumberInputCell") as! HDNumberInputCell
            let cell = cellOriginal as! HDNumberInputCell
            cell.delegate = self
            cell.precisionBox = 0
            cell.precisionBag = 2
        case 1,2,3,4,100:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
//            let cell = cellOriginal as! HDProductInfocell
        case 202:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDSwitchCell") as! HDSwitchCell
            let cell = cellOriginal as! HDSwitchCell
            cell.delegate = self

        default:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell

        }
        if !self.reuseFlag {
            cellOriginal?.clearContent()
        }
        cellOriginal!.titleView.text = dataArray[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
        return cellOriginal!
    }
    //MARK: - tableViewDelegate
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 2:
            return UIView(frame: CGRect(x: 0, y: 0, width: KscreenWidth, height: 0.1))
        default:
            return nil
        }
    }
}
